const express =require('express')
const Router  =express.Router()
const model=require('./module')
const User=model.getModels('user')
const Chat=model.getModels('chat')
const _filter={'pwd':0,'__v':0,"salt":0}
const utils=require('utility')
Router.get('/list',(req,res)=>{
    // User.remove({},(e,d)=>{})
    const {type} =req.query||''
    returnList(type)
    .then(doc=>{
        return res.json(doc)
    }).catch(
        err=>{
            return res.json({code:1})
        }
    )
})
Router.get('/updateType',(req,res)=>{
    User.update(
        {'type':'genuuis'},
        {$set:{'type':'genius'}},
        {multi:true},
        (e,d)=>{
            if(e){
                return res.json({code:1})
            }else{
                 returnList()
                .then(doc=>{
                    return res.json(doc)
                }).catch(
                    err=>{
                        return res.json(err)
                    }
                )
            }
        }
    )
})

Router.post('/update',(req,res)=>{
    const {userid}=req.cookies;
    if(!userid){
        return res.json({code:1})
    }

    let body=req.body;
    //空的不更新
    for(var i in body){
        if(body[i]==''){
            delete body[i]
        }
    }
    User.findByIdAndUpdate(userid,body,function(err,doc){
		const data = Object.assign({},{
			user:doc.user,
			type:doc.type
		},body)
		return res.json({code:0,data})
	})
    
})
Router.get('/info',function (req,res) {
    const {userid} =req.cookies;
    if(!userid){
        return res.json({code:1})
    }
    User.findOne({_id:userid},_filter,(err,doc)=>{
        if(err){
            return res.json({code:1,msg:'后端出错了'})
        }
        if(doc){
            return res.json({code:0,data:doc})
            // setTimeout(()=>{

                // return res.json({code:0,data:doc})
            // },3000)
        }
    })
    
})
Router.post('/login',(req,res)=>{
    const {user,pwd}=req.body
    
    User.findOne({user},(err,doc)=>{
        if(doc){
            let salt=doc.salt
            User.findOne({user,pwd:md5Pwd(pwd,salt).pwd},_filter,(e,d)=>{
                if(!d){
                    return res.json({code:1,msg:'用户名或者密码错误'})
                }
                res.cookie('userid',d._id)
                return res.json({code:0,data:d})
            })
        }else{
            return res.json({code:1,msg:'用户名或者密码错误'})
        }
    })
})
Router.post('/register',function (req,res) {
    console.log(req.body);
    const {user,pwd,type}=req.body
    User.findOne({user},function (err,doc) {
        if(doc){
            return res.json({code:1,msg:'用户名重复'})
        }
        let pwdObj=md5Pwd(pwd)
        const userModel=new User({user,type,pwd:pwdObj.pwd,salt:pwdObj.salt});
        userModel.save((e,d)=>{
            if(e){
                return res.json({code:1,msg:'后端出错了'})
            }
            const{user,type,_id}=d;
            res.cookie('userid',_id)
            return res.json({code:0,data:{user,type,_id}})
        })
        // User.create({user,pwd:pwdObj.pwd,salt:pwdObj.salt,type,},function (e,d) {
        //     if(e){
        //         return res.json({code:1,msg:'后端出错了'})
        //     }
        //     const{user,type,_id}=d;
        //     res.cookie('userid',_id)
        //     console.log('=================')
        //     console.log(_id)
        //     return res.json({code:0,data:{user,type,_id}})
        // })
    })
})

Router.post('/getmsglist',(req,res)=>{
    const user=req.cookies.userid;
    const query=req.body.userTo?{_id:req.body.userTo}:{}
    let users={};
    //查询条件 聊天对象的名字
    if(req.body.userTo){
        User.find(
            query
        ,(e,userdoc)=>{
            if(!e){
                //这里查出来所有用户信息 这里优化一下 没必要查出所有用户信息
                userdoc.forEach(v=>{
                    users.from_name=v.user
                    console.log(users);
                    
                    // users[v._id]={name:v.user,avatar:v.avatar}
                })
                
                //这里查询条件 from to都是跟当前用户一致
                Chat.find({'$or':[{from:user},{to:user}]},(err,doc)=>{
                    if(!err){
                        
                        return res.json({code:0,msgs:doc,users:users})
                    }
                })
            }
            
            
        })
    }else{
        Chat.find({'$or':[{from:user},{to:user}]},(err,doc)=>{
            if(!err){
                
                return res.json({code:0,msgs:doc,users:''})
            }
        })
    }
    
    
    // {'$or':[{from:user,to:user}]}
    
})
Router.get('/removechat',(req,res)=>{
    Chat.remove({},(err,doc)=>{
        if(!err){
            return res.json({code:0,data:doc})
        }
    })
})
Router.post('/readmsg',(req,res)=>{
    const userid=req.cookies.userid;
    const {from} =req.body;
    Chat.update(
        {from,to:userid},{'$set':{read:true}},{multi:true}
        ,(err,doc)=>{
        // console.log(doc)
        if(!err){
            return res.json({code:0,num:doc.nModified})
        }
        return res.json({code:1,msg:'修改失败'})
    })

})
function md5Pwd(pwd,salt) {
    salt=salt||''
    let strSource='abcdefghijklmnopqrstuvwxyz!~#$%^&*()1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    if(!salt){
        for(var i=0;i<32;i++){
            salt+=strSource.substr(Math.floor(Math.random()*strSource.length)+1,1)
        }
    }
    console.log(salt);
    
    return {
        pwd:utils.md5(utils.md5(pwd+salt)),
        salt:salt
    }
    
}

async function returnList(type){
    // return new Promise((resolve,reject)=>{
        type=type?{type}:{}
        console.log(type);
        
        try {
            let res= await User.find(type)
            return {code:0,data:res}
        } catch (error) {
            return {code:1}
        }
        
        // if(err){
        //     return err 
        // }else{
        //     return doc
        // }
        // User.find({},(err,doc)=>{
        //     if(err){
        //         reject(err)
        //     }else{
        //         resolve(doc)
        //     }
        // })
    // })
}
    
module.exports=Router